#include "mainwindow.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QTextEdit>
#include <QPushButton>
#include <QPlainTextEdit>
#include <QLabel>
#include <QFileDialog>
#include <QMessageBox>
#include <QDebug>
#include <QGroupBox>
#include <QGridLayout>
#include <QStringConverter>
#include <QSettings>
#include <QCoreApplication>
#include <QCheckBox>
#include "prompteditor.h"
#include <QSysInfo>
#include <QTimer>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_checkServerTimer(nullptr)
{
    m_settingsPath = QCoreApplication::applicationDirPath() + "/aiservicesettings.ini";
    
    initUI();
    loadSettings();
    
    // 连接信号槽
    connect(m_testButton, &QPushButton::clicked, this, &MainWindow::testApiConnection);
    connect(m_selectButton, &QPushButton::clicked, this, &MainWindow::selectSrtFile);
    connect(m_translateButton, &QPushButton::clicked, this, &MainWindow::startTranslate);
    connect(m_editPromptButton, &QPushButton::clicked, this, [this]() {
        PromptEditor editor(this);
        editor.exec();
    });
}

MainWindow::~MainWindow()
{
    if (m_checkServerTimer) {
        m_checkServerTimer->stop();
        delete m_checkServerTimer;
    }
}

void MainWindow::initUI()
{
    // 创建中心部件
    QWidget* centralWidget = new QWidget(this);
    QVBoxLayout* mainLayout = new QVBoxLayout(centralWidget);
    setCentralWidget(centralWidget);
    
    // 创建标签页控件
    m_tabWidget = new QTabWidget(this);
    mainLayout->addWidget(m_tabWidget);
    
    // 创建各个标签页
    createSettingsTab();
    createTranslationTab();
    
    // 设置窗口属性
    setWindowTitle("字幕翻译工具");
    resize(800, 600);
}

void MainWindow::createSettingsTab()
{
    QWidget* settingsTab = new QWidget(this);
    QVBoxLayout* settingsLayout = new QVBoxLayout(settingsTab);
    
    // OpenAI设置区域
    QGroupBox* apiGroup = new QGroupBox("OpenAI设置", settingsTab);
    QGridLayout* apiLayout = new QGridLayout(apiGroup);
    
    m_apiKeyEdit = new QLineEdit(settingsTab);
    m_apiKeyEdit->setPlaceholderText("API Key");
    m_urlEdit = new QLineEdit(settingsTab);
    m_modelEdit = new QLineEdit(settingsTab);
    m_testButton = new QPushButton("测试连接", settingsTab);
    m_testResult = new QLineEdit(settingsTab);
    m_testResult->setReadOnly(true);
    
    apiLayout->addWidget(new QLabel("API Key:", settingsTab), 0, 0);
    apiLayout->addWidget(m_apiKeyEdit, 0, 1);
    apiLayout->addWidget(new QLabel("URL:", settingsTab), 1, 0);
    apiLayout->addWidget(m_urlEdit, 1, 1);
    apiLayout->addWidget(new QLabel("Model:", settingsTab), 2, 0);
    apiLayout->addWidget(m_modelEdit, 2, 1);
    apiLayout->addWidget(m_testButton, 3, 0);
    apiLayout->addWidget(m_testResult, 3, 1);
    
    settingsLayout->addWidget(apiGroup);
    
    // 本地AI服务设置区域
    QGroupBox* localAIGroup = new QGroupBox("本地AI服务设置", settingsTab);
    QGridLayout* localAILayout = new QGridLayout(localAIGroup);
    
    m_useLocalAICheck = new QCheckBox("使用本地AI服务", settingsTab);
    m_modelPathEdit = new QLineEdit(settingsTab);
    m_modelPathEdit->setPlaceholderText("AI模型文件路径");
    m_selectModelButton = new QPushButton("选择模型", settingsTab);
    m_hostEdit = new QLineEdit(settingsTab);
    m_portEdit = new QLineEdit(settingsTab);
    m_tempEdit = new QLineEdit(settingsTab);
    m_contextSizeEdit = new QLineEdit(settingsTab);
    m_nglEdit = new QLineEdit(settingsTab);
    
    localAILayout->addWidget(m_useLocalAICheck, 0, 0, 1, 2);
    localAILayout->addWidget(new QLabel("模型路径:", settingsTab), 1, 0);
    QHBoxLayout* modelPathLayout = new QHBoxLayout();
    modelPathLayout->addWidget(m_modelPathEdit);
    modelPathLayout->addWidget(m_selectModelButton);
    localAILayout->addLayout(modelPathLayout, 1, 1);
    localAILayout->addWidget(new QLabel("主机地址:", settingsTab), 2, 0);
    localAILayout->addWidget(m_hostEdit, 2, 1);
    localAILayout->addWidget(new QLabel("端口:", settingsTab), 3, 0);
    localAILayout->addWidget(m_portEdit, 3, 1);
    localAILayout->addWidget(new QLabel("温度:", settingsTab), 4, 0);
    localAILayout->addWidget(m_tempEdit, 4, 1);
    localAILayout->addWidget(new QLabel("上下文大小:", settingsTab), 5, 0);
    localAILayout->addWidget(m_contextSizeEdit, 5, 1);
    localAILayout->addWidget(new QLabel("NGL:", settingsTab), 6, 0);
    localAILayout->addWidget(m_nglEdit, 6, 1);
    
    // 添加到主布局
    settingsLayout->addWidget(localAIGroup);
    
    // 添加恢复默认设置按钮
    m_resetButton = new QPushButton("恢复默认设置", settingsTab);
    settingsLayout->addWidget(m_resetButton);
    
    // 连接信号槽
    connect(m_useLocalAICheck, &QCheckBox::toggled, this, &MainWindow::onLocalAIToggled);
    connect(m_selectModelButton, &QPushButton::clicked, this, &MainWindow::selectModelFile);
    connect(m_resetButton, &QPushButton::clicked, this, [this]() {
        if (QMessageBox::question(this, "确认", "确定要恢复默认设置吗？") == QMessageBox::Yes) {
            setDefaultValues();
            updateLog("已恢复默认设置");
        }
    });
    
    // 设置默认值
    setDefaultValues();
    
    settingsLayout->addStretch();
    
    m_tabWidget->addTab(settingsTab, "AI服务设置");
}

void MainWindow::createTranslationTab()
{
    QWidget* translationTab = new QWidget(this);
    QVBoxLayout* translationLayout = new QVBoxLayout(translationTab);
    
    // 文件选择区域
    QGroupBox* fileGroup = new QGroupBox("字幕文件", translationTab);
    QHBoxLayout* fileLayout = new QHBoxLayout(fileGroup);
    
    m_srtPathEdit = new QLineEdit(translationTab);
    m_srtPathEdit->setPlaceholderText("选择SRT字幕文件");
    m_selectButton = new QPushButton("浏览", translationTab);
    
    fileLayout->addWidget(m_srtPathEdit);
    fileLayout->addWidget(m_selectButton);
    
    translationLayout->addWidget(fileGroup);
    
    // 字幕显示区域
    QGroupBox* textGroup = new QGroupBox("字幕内容", translationTab);
    QHBoxLayout* textLayout = new QHBoxLayout(textGroup);
    
    m_originalText = new QTextEdit(translationTab);
    m_originalText->setReadOnly(true);
    m_translatedText = new QTextEdit(translationTab);
    m_translatedText->setReadOnly(true);
    
    textLayout->addWidget(m_originalText);
    textLayout->addWidget(m_translatedText);
    
    // 添加滚动条同步
    connect(m_originalText->verticalScrollBar(), &QScrollBar::valueChanged, 
            m_translatedText->verticalScrollBar(), &QScrollBar::setValue);
    connect(m_translatedText->verticalScrollBar(), &QScrollBar::valueChanged, 
            m_originalText->verticalScrollBar(), &QScrollBar::setValue);
    
    translationLayout->addWidget(textGroup);
    
    // 操作按钮区域
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    m_keepHistoryCheck = new QCheckBox("保留历史记录用于参考", translationTab);
    m_keepHistoryCheck->setChecked(true);
    m_translateButton = new QPushButton("开始翻译", translationTab);
    m_editPromptButton = new QPushButton("编辑提示", translationTab);
    
    buttonLayout->addWidget(m_keepHistoryCheck);
    buttonLayout->addWidget(m_editPromptButton);
    buttonLayout->addWidget(m_translateButton);
    
    translationLayout->addLayout(buttonLayout);
    
    // 日志显示区域
    QGroupBox* logGroup = new QGroupBox("运行日志", translationTab);
    QVBoxLayout* logLayout = new QVBoxLayout(logGroup);
    
    m_logText = new QPlainTextEdit(translationTab);
    m_logText->setReadOnly(true);
    
    logLayout->addWidget(m_logText);
    translationLayout->addWidget(logGroup);
    
    // 设置翻译器的日志输出
    m_translator.setLog(m_logText);
    
    m_tabWidget->addTab(translationTab, "翻译界面");
}

void MainWindow::loadSettings()
{
    QSettings settings(m_settingsPath, QSettings::IniFormat);
    
    // 先设置默认值
    setDefaultValues();
    
    // 然后从配置文件加载保存的值
    m_urlEdit->setText(settings.value("OpenAI/url", m_urlEdit->text()).toString());
    m_apiKeyEdit->setText(settings.value("OpenAI/apiKey", m_apiKeyEdit->text()).toString());
    m_modelEdit->setText(settings.value("OpenAI/model", m_modelEdit->text()).toString());
    
    m_modelPathEdit->setText(settings.value("LocalAI/modelPath", m_modelPathEdit->text()).toString());
    m_hostEdit->setText(settings.value("LocalAI/host", m_hostEdit->text()).toString());
    m_portEdit->setText(settings.value("LocalAI/port", m_portEdit->text()).toString());
    m_tempEdit->setText(settings.value("LocalAI/temp", m_tempEdit->text()).toString());
    m_contextSizeEdit->setText(settings.value("LocalAI/contextSize", m_contextSizeEdit->text()).toString());
    m_nglEdit->setText(settings.value("LocalAI/ngl", m_nglEdit->text()).toString());
    
    qDebug() << "从" << m_settingsPath << "加载设置";
}

void MainWindow::saveSettings()
{
    QSettings settings(m_settingsPath, QSettings::IniFormat);
    
    // 保存当前设置
    settings.setValue("OpenAI/url", m_urlEdit->text());
    settings.setValue("OpenAI/apiKey", m_apiKeyEdit->text());
    settings.setValue("OpenAI/model", m_modelEdit->text());
    
    // 保存本地AI服务设置
    settings.setValue("LocalAI/modelPath", m_modelPathEdit->text());
    settings.setValue("LocalAI/host", m_hostEdit->text());
    settings.setValue("LocalAI/port", m_portEdit->text());
    settings.setValue("LocalAI/temp", m_tempEdit->text());
    settings.setValue("LocalAI/contextSize", m_contextSizeEdit->text());
    settings.setValue("LocalAI/ngl", m_nglEdit->text());
    
    settings.sync();
    
    qDebug() << "保存设置到" << m_settingsPath;
}

void MainWindow::testApiConnection()
{
    QString apiKey = m_apiKeyEdit->text();
    QString url = m_urlEdit->text();
    QString model = m_modelEdit->text();
    
    m_logText->clear();

    updateLog("正在测试API连接...");
    
    // 保存当前设置
    saveSettings();
    
    OpenaiManager* manager = OpenaiManager::getInstance();
    bool success = manager->testApi(url, apiKey, model);
    
    if (success) {
        m_testResult->setText("连接成功");
        m_testResult->setStyleSheet("color: green;");
        updateLog("API连接测试成功");
    } else {
        m_testResult->setText("连接失败");
        m_testResult->setStyleSheet("color: red;");
        updateLog("API连接测试失败");
    }
}

void MainWindow::selectSrtFile()
{
    QString filePath = QFileDialog::getOpenFileName(
        this,
        "选择SRT字幕文件",
        QString(),
        "字幕文件 (*.srt);;所有文件 (*.*)"
    );
    
    if (!filePath.isEmpty()) {
        m_srtPathEdit->setText(filePath);
        updateLog("已选择字幕文件: " + filePath);
        
        // 读取并显示原文
        QFile file(filePath);
        if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QTextStream in(&file);
            in.setEncoding(QStringConverter::Utf8);
            m_originalText->setText(in.readAll());
            file.close();
        }
    }
}

void MainWindow::startTranslate()
{
    QString filePath = m_srtPathEdit->text();
    QString url = m_urlEdit->text();
    QString apiKey = m_apiKeyEdit->text();
    QString model = m_modelEdit->text();
    
    m_logText->clear();

    if (filePath.isEmpty() || url.isEmpty() || apiKey.isEmpty() || model.isEmpty()) {
        QMessageBox::warning(this, "警告", "请填写所有必要信息");
        return;
    }
    
    // 保存当前设置
    saveSettings();
    
    updateLog("开始翻译字幕...");
    m_translateButton->setEnabled(false);
    
    bool keepHistory = m_keepHistoryCheck->isChecked();
    bool success = m_translator.translate(filePath, url, apiKey, model, keepHistory);
    
    if (success) {
        updateLog("翻译完成");
        // 显示翻译结果
        QString translatedPath = filePath;
        translatedPath.replace(".srt", "_translated.srt");
        QFile file(translatedPath);
        if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QTextStream in(&file);
            in.setEncoding(QStringConverter::Utf8);
            m_translatedText->setText(in.readAll());
            file.close();
        }
    } else {
        updateLog("翻译失败");
    }
    
    m_translateButton->setEnabled(true);
}

void MainWindow::updateLog(const QString& log)
{
    m_logText->appendPlainText(log);
    qDebug() << log;
}

void MainWindow::onLocalAIToggled(bool checked)
{   
    if (checked) {
        // 根据操作系统获取程序路径
        QString programPath;
        if (QSysInfo::productType() == "windows") {
            programPath = QCoreApplication::applicationDirPath() + "/llama_bin/llama-server.exe";
        } else {
            programPath = QCoreApplication::applicationDirPath() + "/llama_bin/llama-server";
        }
        
        // 启动本地AI服务
        bool success = m_llamaServer.startServer(
            programPath,
            m_modelPathEdit->text(),
            m_hostEdit->text(),
            m_portEdit->text(),
            m_tempEdit->text(),
            m_contextSizeEdit->text(),
            m_nglEdit->text()
        );

        if (!success) {
            updateLog("本地AI服务启动失败");
            QMessageBox::critical(this, "错误", "本地AI服务启动失败，请检查设置和程序路径");
            m_useLocalAICheck->setChecked(false);  // 启动失败时自动取消选中
            return;
        }

        // 创建定时器检查服务是否真正启动
        m_checkServerTimer = new QTimer(this);
        m_checkServerTimer->setSingleShot(true);  // 只触发一次
        connect(m_checkServerTimer, &QTimer::timeout, this, [this]() {
            if (!m_llamaServer.isRunning()) {
                updateLog("本地AI服务启动错误");
                QMessageBox::critical(this, "错误", "本地AI服务启动错误，请检查设置和程序路径");
                m_useLocalAICheck->setChecked(false);
                m_llamaServer.stopServer();
            } else {
                updateLog("本地AI服务已成功启动并运行");
                QMessageBox::information(this, "成功", "本地AI服务已启动");
            }
        });
        m_checkServerTimer->start(1000);  // 1秒后检查

    } else {
        // 停止本地AI服务
        m_llamaServer.stopServer();
        updateLog("本地AI服务已停止");
    }
}

void MainWindow::selectModelFile()
{
    QString filePath = QFileDialog::getOpenFileName(
        this,
        "选择AI模型文件",
        m_modelPathEdit->text(),
        "GGUF模型文件 (*.gguf);;所有文件 (*.*)"
    );
    
    if (!filePath.isEmpty()) {
        m_modelPathEdit->setText(filePath);
        updateLog("已选择模型文件: " + filePath);
    }
}

// 新增：设置默认值的函数
void MainWindow::setDefaultValues()
{
    // OpenAI设置默认值
    m_urlEdit->setText("http://127.0.0.1:11434/v1/chat/completions");
    m_apiKeyEdit->setText("123456");
    m_modelEdit->setText("qwen2.5:3b-instruct-q8_0");
    
    // 本地AI服务设置默认值
    m_useLocalAICheck->setChecked(false);  // 始终默认为关闭
    m_modelPathEdit->setText(QCoreApplication::applicationDirPath() + "/model/model.GGUF");
    m_hostEdit->setText("127.0.0.1");
    m_portEdit->setText("11434");
    m_tempEdit->setText("0.7");
    m_contextSizeEdit->setText("2048");
    m_nglEdit->setText("100");
}
